package com.nx.biz.shopify.sdk.hualeiSdk;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.nx.biz.shopify.api.RedisKeys;
import com.nx.biz.shopify.sdk.hualeiSdk.model.*;
import com.nx.biz.shopify.tools.HttpRestClientTool;
import com.nx.common.exception.BusinessException;
import com.nx.common.result.HttpClientResult;
import com.nx.common.tools.CheckTools;
import com.nx.common.tools.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Component
@Slf4j
public class HualeiClient {
//    public static String URL1 = "http://118.25.228.118:8082";
//    public static String URL2 = "http://118.25.228.118:8089";
    public static String URL1 = "http://134.175.219.102:8082";
    public static String URL2 = "http://134.175.219.102:8089";
    private static String userName;
    private static String password;
    private static String customerId;
    private static String customerUserId;
    private static List<HualeiProduct> hualeiProductList = new ArrayList<>();

    private Gson GSON = new Gson();
    @Autowired
    private RedisUtil redisUtil;

//    public static void init(String userName, String password)  {
//        this.userName = userName;
//        this.setUserName(userName);
//        this.setPassword(password);
//
//        this.authCache();
//        this.getProductListCache();
//    }

    /** 认证 */
    public HualeiAuthInfo auth(String userName, String password) throws IOException {
        String url = URL1 + "/selectAuth.htm?username=" + userName + "&password=" + password;

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");

        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        if (clientResult.getCode() != 200) {
            throw new BusinessException(GSON.toJson(clientResult));
        }
        HualeiAuthInfo hualeiAuthInfo = GSON.fromJson(clientResult.getContent(), HualeiAuthInfo.class);
        return hualeiAuthInfo;
    }

    /** 获取产品列表 */
    public List<HualeiProduct> getProductList() throws IOException {
        String url = URL1 + "/getProductList.htm";

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");

        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        if (clientResult.getCode() != 200) {
            throw new BusinessException(GSON.toJson(clientResult));
        }
        List<HualeiProduct> hualeiProductList = GSON.fromJson(clientResult.getContent(), new TypeToken<List<HualeiProduct>>(){}.getType());
        return hualeiProductList;
    }

    /** 创建订单 */
    public HualeiOrderCreateResp createOrder(HualeiOrderCreateReq hualeiOrderCreateReq) throws IOException {
        String strUrl = URL1 + "/createOrderApi.htm";
        String strParam = GSON.toJson(hualeiOrderCreateReq);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/x-www-form-urlencoded");

        String paramValue = URLEncoder.encode(GSON.toJson(hualeiOrderCreateReq), "UTF-8");
        String paramStr = "param=" + paramValue;


        HttpClientResult httpClientResult = HttpRestClientTool.post(strUrl, paramStr, "application/x-www-form-urlencoded", headers);
        HualeiOrderCreateResp hualeiOrderCreateResp = GSON.fromJson(httpClientResult.getContent(), HualeiOrderCreateResp.class);
        hualeiOrderCreateResp.setMessage(java.net.URLDecoder.decode(hualeiOrderCreateResp.getMessage(), "UTF-8"));

        return hualeiOrderCreateResp;
    }

    /** 获取跟踪号 */
    public List<HualeiTrackNumberResp> getTrackingNumberBatch(List<String> orderIdList) throws IOException {
        List<HualeiTrackNumberResp> hualeiTrackNumberRespList = new ArrayList<>();

        String url = URL1 + "/getOrderTrackingNumberBatch.htm?documentCode=" + String.join(",", orderIdList);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");

        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        if (clientResult.getCode() != 200) {
            throw new BusinessException(GSON.toJson(clientResult));
        }
        JsonObject jsonObject = (JsonObject) new JsonParser().parse(clientResult.getContent()).getAsJsonObject();
        JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();
        for(JsonElement obj : jsonArray ){
            HualeiTrackNumberResp hualeiTrackNumberResp = GSON.fromJson( obj , HualeiTrackNumberResp.class);
            hualeiTrackNumberRespList.add(hualeiTrackNumberResp);
        }

        return hualeiTrackNumberRespList;
    }

    /** 获取运踪 */
    // 这个接口，传入tracking number list 和 order id list都可以
    public List<HualeiTrackResp> selectTrackBatch(List<String> docIdList) throws IOException {
        String url = URL1 + "/selectTrack.htm?documentCode=" + String.join(",", docIdList);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");

        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        if (clientResult.getCode() != 200) {
            throw new BusinessException(GSON.toJson(clientResult));
        }
        List<HualeiTrackResp> hualeiTrackRespList = GSON.fromJson(clientResult.getContent(), new TypeToken<List<HualeiTrackResp>>(){}.getType());

        return hualeiTrackRespList;
    }


    /** --------------------------------------------- 初始化&认证 --------------------------------------------- */
    public List<HualeiProduct> getProductListCache() {
        List<HualeiProduct> hualeiProductList = null;

        Object object = redisUtil.get(RedisKeys.hualeiProductList);
        if (CheckTools.isNullOrEmpty(object)) {
            try {
                hualeiProductList = this.getProductList();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (hualeiProductList.size() > 0) {
                redisUtil.set(RedisKeys.hualeiProductList, GSON.toJson(hualeiProductList));
                object = redisUtil.get(RedisKeys.hualeiProductList);
                HualeiProduct[] array =  GSON.fromJson(GSON.toJson(object), HualeiProduct[].class);
                hualeiProductList = Arrays.asList(array);
                log.info("获取并存储到redis中的 hl product-list: {}", hualeiProductList);
            } else {
                log.error("未获取到华磊的产品列表");
                return null;
            }
        } else {
            HualeiProduct[] array =  GSON.fromJson(GSON.toJson(object), HualeiProduct[].class);
            hualeiProductList = Arrays.asList(array);
            log.info("获取redis中的 hl product-list: {}", hualeiProductList);
        }

        return hualeiProductList;
    }

    public HualeiAuthInfo authCache() {
        HualeiAuthInfo hualeiAuthInfo = null;
        Object object = redisUtil.get(RedisKeys.hualeiAuthInfo);
        if (CheckTools.isNullOrEmpty(object)) {
            try {
                hualeiAuthInfo = this.auth("test", "123456");
            }
            catch (IOException e) {
                e.printStackTrace();
            }

            if (CheckTools.isNotNullOrEmpty(hualeiAuthInfo) && hualeiAuthInfo.getAck().equals("true")) {
                redisUtil.set(RedisKeys.hualeiAuthInfo, GSON.toJson(hualeiAuthInfo));
                object = redisUtil.get(RedisKeys.hualeiAuthInfo);
                hualeiAuthInfo = GSON.fromJson((String) object, HualeiAuthInfo.class);
                log.info("获取并存储到redis中的 hl-auth-info: {}", hualeiAuthInfo);
            } else {
                log.error("未获取到华磊auth信息");
                return null;
            }
        } else {
            hualeiAuthInfo = GSON.fromJson((String) object, HualeiAuthInfo.class);
            log.info("获取redis中的 hl authCache info: {}", hualeiAuthInfo);
        }

        return hualeiAuthInfo;
    }
}
